package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.service.CommissionService;
import com.example.service.CouponService;
import com.example.service.GoodsService;
import com.example.service.UserService;
import com.example.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * @description: 商品
 * @author: xxx
 * @create: 2021/7/19 09:30
 */
@RestController
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    private GoodsService service;
    @Autowired
    private CommissionService commissionService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private UserService userService;

    /**
     * @param json
     * @description: 分页
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getPage")
    public Result getPage(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        jsonObject.put("userId", TokenTool.getUserId());
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapVip = userService.selectVipByUserId(TokenTool.getUserId());
        if (mapVip != null && mapVip.get("vip").toString().equals("1")) {
            map.put("id", "1");//会员抢购时间
        } else {
            map.put("id", "2");//普通抢购时间
        }
        Map<String, Object> time = service.getTimeById(map);
        jsonObject.put("startTime", time.get("startTime"));
        jsonObject.put("endTime", time.get("endTime"));
        List<Map<String, Object>> list = service.getListSale(jsonObject);
        int total = service.getCountSale(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    /**
     * @param json
     * @description: 收益分页
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getPageGoodsAddedEarnings")
    public Result getPageGoodsAddedEarnings(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        jsonObject.put("userId", TokenTool.getUserId());
        List<Map<String, Object>> list = service.getListGoodsAddedEarnings(jsonObject);
        int total = service.getCountGoodsAddedEarnings(jsonObject);

        return ResultUtil.successPage(list, total);
    }

    /**
     * @param map
     * @description: 当日收益
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getEarningsToday")
    public Result getEarningsToday(@RequestBody Map<String, Object> map) {

        map.put("userId", TokenTool.getUserId());
        return ResultUtil.success(service.getEarningsToday(map));
    }

    /**
     * @param map
     * @description: 累计收益
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/7/19 09:30
     */
    @RequestMapping("getEarningsAll")
    public Result getEarningsAll(@RequestBody Map<String, Object> map) {

        map.put("userId", TokenTool.getUserId());
        return ResultUtil.success(service.getEarningsAll(map));
    }

    /**
     * @param
     * @description: 列表
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getList")
    public Result getList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        jsonObject.put("userId", TokenTool.getUserId());
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapVip = userService.selectVipByUserId(TokenTool.getUserId());
        if (mapVip != null && mapVip.get("vip").toString().equals("1")) {
            map.put("id", "1");//会员抢购时间
        } else {
            map.put("id", "2");//普通抢购时间
        }
        Map<String, Object> time = service.getTimeById(map);
        jsonObject.put("startTime", time.get("startTime"));
        jsonObject.put("endTime", time.get("endTime"));
        return ResultUtil.success(service.getListSale(jsonObject));
    }

    /**
     * @param
     * @description: 我的商品
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getMyList")
    public Result getMyList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        jsonObject.put("uId", TokenTool.getUserId());
        if (jsonObject.get("addeds") != null) {
            jsonObject.put("addeds", "1,2");
        }
        List<Map<String, Object>> list = service.getList(jsonObject);
        int total = service.getCount(jsonObject);
        return ResultUtil.successPage(list, total);
    }

    /**
     * @param
     * @description: 申请上架
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("apply")
    @Transactional(rollbackFor = Exception.class)
    public Result apply(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapGoods = service.getById(map);
        Map<String, Object> mapGoodsAdded = new HashMap<>();
        String userId = TokenTool.getUserId();
        mapGoodsAdded.put("id", IDTool.getUUID32());
        mapGoodsAdded.put("price", mapGoods.get("price"));//当前价格
        mapGoodsAdded.put("goodsId", mapGoods.get("id"));//商品id
        // 判断商品状态
        if (mapGoods.get("added").toString().equals("2") && mapGoods.get("uId").toString().equals(userId)) {
            Map<String, Object> mapNew = new HashMap<>();
            mapNew.put("id", mapGoods.get("id"));
            mapNew.put("added", 4);
            mapNew.put("addTime", new Date());
            double addPrice = Double.parseDouble(mapGoods.get("addPrice").toString());//上架费
            mapGoodsAdded.put("addPrice", addPrice);//上架费
            BigDecimal addPriceBig = new BigDecimal(Double.valueOf(addPrice));

            // 如果用户使用了优惠券
            if (map.get("couponId") != null) {
                mapGoodsAdded.put("couponId", map.get("couponId"));//优惠券id
                Map<String, Object> mapCouponId = new HashMap<>();
                mapCouponId.put("id", map.get("couponId"));
                mapCouponId.put("userId", userId);
                Map<String, Object> mapCoupon = couponService.getMyById(mapCouponId);
                double moneyCoupon = Double.parseDouble(mapCoupon.get("money").toString());
                if (moneyCoupon > addPrice) {
                    return ResultUtil.error(-500, "优惠券面值过大不符合使用条件");
                } else {
                    BigDecimal moneyCouponBig = new BigDecimal(Double.valueOf(moneyCoupon));
                    addPriceBig = addPriceBig.subtract(moneyCouponBig).setScale(2, BigDecimal.ROUND_HALF_UP);//减法
                    mapCouponId.put("status", 2);
                    couponService.updateCouponDetail(mapCouponId);//核销优惠券
                }
            }

            // 申请上架
            mapNew.put("addTime", new Date());
            service.update(mapNew);//商品变成待上架状态
            mapGoodsAdded.put("userId", userId);
            mapGoodsAdded.put("je", addPriceBig);//实缴金额
            service.saveGoodsAdded(mapGoodsAdded);//申请记录
        } else {
            return ResultUtil.error(-500, "不符合上架条件");
        }

        return ResultUtil.success(mapGoodsAdded.get("id"));
    }

    /**
     * @param map
     * @description: 详情
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getById")
    public Result getById(@RequestBody Map<String, Object> map) {

        return ResultUtil.success(service.getById(map));
    }

    /**
     * @param map
     * @description: 获取普通抢购时间
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/21 9:19
     */
    @RequestMapping("getTime")
    public Result getTime(@RequestBody Map<String, Object> map) {
        map.put("id", 2);
        return ResultUtil.success(service.getTimeById(map));
    }

    /**
     * @param map
     * @description: 获取vip抢购时间
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/6/21 9:19
     */
    @RequestMapping("getVipTime")
    public Result getVipTime(@RequestBody Map<String, Object> map) {
        map.put("id", 1);
        return ResultUtil.success(service.getTimeById(map));
    }

    /**
     * @param
     * @description: 申请上架列表
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("getGoodsAddedPage")
    public Result getGoodsAddedList(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        Page.getPage(jsonObject);
        jsonObject.put("userId", TokenTool.getUserId());
        jsonObject.put("status", 1);
        List<Map<String, Object>> list = service.getListGoodsAdded(jsonObject);
        int total = service.getCountGoodsAdded(jsonObject);
        return ResultUtil.successPage(list, total);
    }

    /**
     * @param
     * @description: 取消上架
     * @return: com.example.common.entity.Result
     * @author: xxx
     * @time: 2021/5/06 09:30
     */
    @RequestMapping("cancelAudit")
    @Transactional(rollbackFor = Exception.class)
    public Result canelAudit(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> mapGoodsAdded = service.getGoodsAddedById(map);
        if (mapGoodsAdded.get("userId").toString().equals(TokenTool.getUserId())) {
            Map<String, Object> mapGoodsId = new HashMap<>();
            mapGoodsId.put("id", mapGoodsAdded.get("goodsId"));
            Map<String, Object> mapGoods = service.getById(mapGoodsId);
            if (mapGoodsAdded.get("status").toString().equals("1")) {
                if (mapGoods.get("added").toString().equals("4")) {
                    if (mapGoodsAdded.get("couponId") != null) {
                        Map<String, Object> mapCouponId = new HashMap<>();
                        mapCouponId.put("id", mapGoodsAdded.get("couponId"));
                        mapCouponId.put("userId", mapGoodsAdded.get("userId"));
                        mapCouponId.put("status", 1);
                        couponService.updateCouponDetail(mapCouponId);//返回核销优惠券
                    }
                    if (mapGoodsAdded.get("money") != null && Double.parseDouble(mapGoodsAdded.get("money").toString()) > 0) {
                        Map<String, Object> mapId = new HashMap<>();
                        mapId.put("id", mapGoodsAdded.get("userId"));
                        Map<String, Object> commissionMap = commissionService.getById(mapId);
                        Map<String, Object> mapCommission = new HashMap<>();
                        mapCommission.put("id", mapGoodsAdded.get("userId"));
                        BigDecimal moneyPrice = new BigDecimal(Double.parseDouble(mapGoodsAdded.get("money").toString()));
                        Double money = Double.parseDouble(commissionMap.get("money").toString());
                        Double oldMoney = Double.parseDouble(commissionMap.get("oldMoney").toString());
                        mapCommission.put("money", new BigDecimal(money).add(moneyPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                        mapCommission.put("oldMoney", new BigDecimal(oldMoney).subtract(moneyPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                        mapCommission.put("uuid", commissionMap.get("uuid"));
                        mapCommission.put("uuidNew", IDTool.getUUID32());
                        Integer result = commissionService.update(mapCommission);//更新佣金
                        if (result <= 0) {
                            throw new Exception("取消上架失败");
                        }
                        //佣金设置为已驳回
                        Map<String, Object> mapWithdraw = new HashMap<>();
                        mapWithdraw.put("id", mapGoodsAdded.get("withdrawId"));
                        mapWithdraw.put("status", 3);
                        commissionService.updateWithdraw(mapWithdraw);
                    }
                    Map<String, Object> mapNew = new HashMap<>();
                    mapNew.put("id", mapGoods.get("id"));
                    mapNew.put("added", 2);
                    service.update(mapNew);
                    map.put("status", 3);
                    service.updateGoodsAdded(map);//更新申请状态
                } else {
                    return ResultUtil.error(-500, "商品状态不符合取消上架条件");
                }
            } else {
                return ResultUtil.error(-500, "已审核过");
            }
        } else {
            return ResultUtil.error(-500, "只能取消自己的上架申请");
        }
        return ResultUtil.success();
    }

    /**
     * @param map
     * @description: 获取当前时间是否符合条件
     * @return: com.example.utils.Result
     * @author: xxx
     * @time: 2022/11/16 20:57
     */
    @RequestMapping("getTimeByNow")
    public Result getTimeByNow(@RequestBody Map<String, Object> map) {

        Integer count = service.getTimeByNow();
        if (count == 1) {
            return ResultUtil.success(true);
        } else {
            return ResultUtil.success(false);
        }

    }
}
